package com.qianguo.shop.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.eva.androidlibrary.widget.mdedittext.MaterialEditText;
import com.qianguo.shop.R;
import com.qianguo.shop.UserManager;
import com.eva.androidlibrary.api.HttpRequestCallback;
import com.qianguo.shop.base.BaseTitleActivity;
import com.eva.androidlibrary.api.entity.ResultData;
import com.eva.androidlibrary.api.entity.UserInfo;
import com.qianguo.shop.constant.ShopKeys;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;


/**
 * 修改昵称
 *
 * @author eva
 * @since 15/10/24
 */
@EActivity(R.layout.activity_modify_nick_name)
public class ModifyNickNameActivity extends BaseTitleActivity {

    @ViewById(R.id.modify_nick_name_edit_text)
    MaterialEditText mEdtNickname;

    @Extra(ShopKeys.EXTRA_KEY_USER)
    UserInfo mUser;

    public static void jumpToModifyNickname(Activity activity, UserInfo user) {
        Intent intent = new Intent(activity, com.qianguo.shop.activity.ModifyNickNameActivity_.class);
        intent.putExtra(ShopKeys.EXTRA_KEY_USER, user);
        activity.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return getString(R.string.nick_name);
    }

    @Override
    protected void initializeUI() {

    }

    @Click(R.id.modify_nick_name_done_button)
    void clickDone() {
        String nickname = mEdtNickname.getText().toString();
        if (TextUtils.isEmpty(nickname)) {
            mEdtNickname.setError(getString(R.string.modify_nick_name_hint));
        } else {
            modifyNickName(nickname);
            closeKeyboard(this);
        }
    }


    @Background
    void modifyNickName(final String nickname) {
        mApp.getApi().modifyNickname(mUser.getToken(), nickname, new HttpRequestCallback<ResultData>() {
            @Override
            public void onSuccess(int code, String msg, ResultData data) {
                mUser.setNickname(nickname);
                UserManager.saveUser(mApp, mUser);
                EventBus.getDefault().post(mUser);
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(ModifyNickNameActivity.this, msg);
            }
        });

    }
}
